<!--待办中心--待执行任务--申请完成（多条项目申请）-->
<template>
  <a-drawer
    title="申请完成"
    :width="1020"
    :visible="drawerVisible"
    :body-style="{ paddingBottom: '80px' }"
    :maskClosable="drawMaskClosable"
    :rowKey="(record) => record.assignmentOid"
    @close="closeApplyComplete"
  >
    <a-table
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      bordered
    >
      <span slot="activityName" slot-scope="text" style="color: #2f54eb">{{
        text
      }}</span>
      <span slot="completePercentTitle"
        ><span style="color: red">*</span> 完成百分比</span
      >
      <span slot="completeTimeTitle"
        ><span style="color: red">*</span> 任务实际完成工期（天）</span
      >
      <span slot="commentTitle"
        ><span style="color: red">*</span> 完成情况说明</span
      >
      <a-input-number
        :min="0"
        :max="100"
        v-model="record.completePercent"
        slot="completePercent"
        slot-scope="text, record"
        style="width: 100%; margin: 0px 0"
        @change="
          onCellChange(record.assignmentOid, record.completePercent, $event)
        "
      />
      <a-input-number
        :min="0"
        :max="100"
        v-model="record.completeTime"
        slot="completeTime"
        slot-scope="text, record"
        style="width: 100%; margin: 0px 0"
        @change="
          onCellChange(record.assignmentOid, record.completeTime, $event)
        "
      />
      <a-input
        v-model="record.comment"
        slot="comment"
        slot-scope="text, record"
        style="width: 100%; margin: 0px 0"
        @change="onCellChange(record.assignmentOid, record.comment, $event)"
      />
    </a-table>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }"
    >
      <a-button :style="{ marginRight: '8px' }" @click="closeApplyComplete">
        取消
      </a-button>
      <a-button type="primary" @click="commitApplyComplete"> 确认 </a-button>
    </div>
  </a-drawer>
</template>
<script>
import { getLastResourceHour, sumResource } from "@api/todoPage";
import _ from "lodash";
export default {
  name: "applyCompleteMore",
  data() {
    return {
      drawerVisible: this.drawerVisible_p,
      textareaValue: "",
      data: [],
      columns: [
        {
          title: "序号",
          dataIndex: "num",
          width: "8%",
          customRender: (text,record,index) => `${index+1}`,
        },
        {
          title: "任务名称",
          dataIndex: "activity.name",
          width: "20%",
          ellipsis: true,
          scopedSlots: { customRender: "activityName" },
        },
        {
          // title: '完成百分比',
          dataIndex: "completePercent",
          width: "22%",
          slots: { title: "completePercentTitle" },
          scopedSlots: { customRender: "completePercent" },
        },
        {
          // title: '任务实际完成工期（天）',
          dataIndex: "completeTime",
          width: "22%",
          slots: { title: "completeTimeTitle" },
          scopedSlots: { customRender: "completeTime" },
        },
        {
          // title: '完成情况说明',
          dataIndex: "comment",
          ellipsis: true,
          slots: { title: "commentTitle" },
          scopedSlots: { customRender: "comment" },
        },
      ],
      pagination: {
        pageSize: 10,
      },
    };
  },
  props: {
    drawerVisible_p: {
      type: Boolean,
      default: false,
    },
    drawMaskClosable: {
      type: Boolean,
      default: false,
    }, //点击蒙层是否允许关闭
  },
  watch: {
    drawerVisible_p(val) {
      this.drawerVisible = val;
    },
  },
  mounted() {
    this.data = this.$store.state.selectedTableData
    this.getLastResourceHourB();
  },
  methods: {
    //关闭抽屉
    closeApplyComplete() {
      this.$emit("closeDraw");
    },
    //获取上一次汇报工时的记录
    getLastResourceHourB() {
      //paramsId入参   nameIdData任务名称+id的新数组
      let paramsId = [],
        aid = {},
        nameIdData = [],
        nameIdDataArr = {};
      let selectData = this.$store.state.selectedTableData; //选中的表格数据
      selectData.map((rec) => {
        nameIdDataArr = {};
        nameIdDataArr.assignmentOid = rec.assignmentOid;
        nameIdDataArr.activityName = rec["activity.name"];
        nameIdData.push(nameIdDataArr);
      });
      // console.log('nameIdData：', nameIdData)
      selectData.map((rec) => {
        aid = {};
        aid.assignmentOid = rec.assignmentOid;
        paramsId.push(aid);
      });
      // console.log('paramsId条件：', paramsId)
      let parm = {
        resources: paramsId,
      };
      getLastResourceHour(parm).then((res) => {
        if (res && res.status === 200) {
          if (res.data && res.data.success == true) {
            if (res.data.data && res.data.data.length > -1) {
              //1.先筛选出无上一次申请记录的数据，拼接新的数组
              let idArr = res.data.data.map((rec) => rec.assignmentOid);
              // console.log('idArr：', idArr)
              let filterData = _.filter(nameIdData, function (o) {
                return idArr.indexOf(o.assignmentOid) === -1;
              });
              // console.log('筛选出的数据：', filterData)
              //2.将筛选的数据组成新的数组，完成百分比、工时设置为为null
              let newFilterData = [],
                newFilterDataOnce = {};
              filterData.map((rec) => {
                newFilterDataOnce = {};
                newFilterDataOnce.assignmentOid = rec.assignmentOid;
                newFilterDataOnce.activityName = rec.activityName;
                newFilterDataOnce.completePercent = 100;
                newFilterDataOnce.completeTime = null;
                newFilterDataOnce.comment = "";
                newFilterData.push(newFilterDataOnce);
              });
              // console.log('筛选出的数据新组成的数组：', newFilterData)
              //3.获取接口返回的数据
              let getData = [],
                getDataOnce = {};
              for (let i = 0; i < res.data.data.length; i++) {
                getDataOnce = {};
                getDataOnce.assignmentOid = res.data.data[i].assignmentOid;
                getDataOnce.activityName = res.data.data[i].activityName;
                getDataOnce.completePercent = res.data.data[i].completePercent;
                getDataOnce.completeTime = res.data.data[i].completeTime;
                getDataOnce.comment = "";
                getData.push(getDataOnce);
              }
              // console.log('后台返回的数组：', getData)
              //4.拼接筛选的数组和接口返回的数据，组成一个新的数组,并按照选择顺序排序
              let newData = _.concat(getData, newFilterData);
              newData = _.sortBy(newData, (rec) => {
                let sortByData = selectData.map((res1) => {
                  return res1.assignmentOid;
                });
                return sortByData.indexOf(rec.assignmentOid);
              });
              //给数组增添序号列
              let newTableData = [],
                newTableDataOnce = {};
              for (let i = 0; i < newData.length; i++) {
                newTableDataOnce = {};
                newTableDataOnce.num = i + 1;
                newTableDataOnce.assignmentOid = newData[i].assignmentOid;
                newTableDataOnce.activityName = newData[i].activityName;
                newTableDataOnce.completePercent = newData[i].completePercent;
                newTableDataOnce.completeTime = newData[i].completeTime;
                newTableDataOnce.comment = newData[i].comment;
                newTableData.push(newTableDataOnce);
              }
              this.data = newTableData;
              // console.log('this.data：', this.data)
            } else {
              this.$message.error(
                "res.data.data不是数组或者res.data.data不存在！"
              );
            }
          } else {
            this.$message.error(res.data.message);
          }
        } else {
          this.$message.error("接口失败！");
        }
      });
    },
    //输入框改变
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.data];
      const target = dataSource.find((item) => item.assignmentOid === key);
      if (target) {
        target[dataIndex] = value;
        this.$store.commit("getApplyTableData", dataSource); //将改变的数据存入vuex
        // console.log('改变输入框的值后的新数据：', dataSource)
      }
    },
    //完成审核，关闭抽屉
    commitApplyComplete() {
      let applyData = this.$store.state.applyTableData; //获取vuex的数据，当做入参
      if (applyData.length > 0) {
        let parmArr = [],
          parmArrOnce = {};
        applyData.map((rec) => {
          parmArrOnce = {};
          parmArrOnce.assignmentOid = rec.assignmentOid;
          parmArrOnce.completePercent = rec.completePercent;
          parmArrOnce.completeTime = rec.completeTime;
          parmArrOnce.comment = rec.comment;
          parmArr.push(parmArrOnce);
        });
        // console.log('parmArr：', parmArr)
        //判断入参是否有空值
        let completePercentArr = parmArr.filter((rec) => {
          return rec.completePercent == null;
        });
        let completeTimeArr = parmArr.filter((rec) => {
          return rec.completeTime == null;
        });
        let commentArr = parmArr.filter((rec) => {
          return rec.comment == "";
        });
        if (
          completePercentArr.length > 0 ||
          completeTimeArr.length > 0 ||
          commentArr.length > 0
        ) {
          this.$message.error("请输入必需项！");
        } else {
          // if (parseInt(this.minPerc) > parseInt(this.perc) || parseInt(this.minPerc) == parseInt(this.perc)) {
          //   this.$message.error('当前汇报百分比必须大于上一次的汇报！')
          // } else {
          let parm = {
            resources: parmArr,
          };
          sumResource(parm).then((res) => {
            // console.log(res)
            if (res && res.status === 200) {
              if (res.data.success == true) {
                this.$message.success("申请成功！");
                this.$store.commit("getApplyTableData", []); //将改变的数据存入vuex
                this.$store.commit("commitApplyAdd"); //刷新抽屉中的数据
                this.$emit("closeDraw");
              } else {
                this.$message.error(res.data.message);
              }
            } else {
              this.$message.error(res.data.message);
            }
          });
          // }
        }
      } else {
        this.$message.error("请输入必需项！");
      }
    },
  },
};
</script>
<style lang="less" scoped>
.applyDraw_temp {
  /deep/ .ant-row {
    margin-bottom: 10px;
  }
  /deep/ .ant-drawer-content-wrapper {
    width: 58vw !important;
  }
  /deep/ .ant-drawer-title {
    color: #333333;
  }
  /deep/ .ant-table-column-title {
    font-size: 14px;
    color: #666666;
  }
  /deep/ .ant-table-bordered .ant-table-thead > tr > th,
  .ant-table-bordered .ant-table-tbody > tr > td {
    border-right: 0px !important;
  }
  /deep/ .ant-table-bordered .ant-table-header > table,
  .ant-table-bordered .ant-table-body > table,
  .ant-table-bordered .ant-table-fixed-left table,
  .ant-table-bordered .ant-table-fixed-right table {
    border: 0px !important;
  }
  /dddp/
    .ant-table-column-has-actions
    .ant-table-column-has-filters
    .ant-table-row-cell-ellipsis
    .ant-table-row-cell-break-word {
    display: flex;
  }
  /deep/ .ant-table-thead > tr > th .anticon-filter,
  .ant-table-thead > tr > th .ant-table-filter-icon {
    position: relative;
    top: -8px;
  }
}
</style>